<template>
  <div class="app-container">
    <el-form ref="collegeFrom" :model="collegeFrom" :rules="rules" label-width="120px">
      <el-form-item label="学院号" prop="id">
        <el-input
          ref="id"
          v-model="collegeFrom.id"
          placeholder="请输入学院号"
          type="text"
        />
      </el-form-item>

      <el-form-item label="学院名" prop="collegeName">
        <el-input
          ref="collegeName"
          v-model="collegeFrom.collegeName"
          placeholder="请输入学院名"
          type="text"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleAddCollege">新增</el-button>
        <el-button @click="handleResetFrom">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { collegeIdPattern, collegeNamePattern } from '@/utils/validate'
import { addCollege } from '@/api/admin/college'

export default {
  name: 'AddCollege',
  data() {
    return {
      collegeFrom: {
        id: '',
        collegeName: ''
      },
      rules: {
        id: [
          { required: true, message: '请输入学院号', trigger: 'blur' },
          { pattern: collegeIdPattern, message: '学院号必须为4位数字', trigger: 'blur' }
        ],
        collegeName: [
          { required: true, message: '请输入学院名', trigger: 'blur' },
          { pattern: collegeNamePattern, message: '学院名必须为中文不超过30个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /**
     * 新增学院信息
     */
    handleAddCollege() {
      this.$refs.collegeFrom.validate(async valid => {
        if (valid) {
          await addCollege(this.collegeFrom)
          this.$message.success('新增成功')
          this.handleResetFrom()
        }
      })
    },
    /**
     * 重置表单
     */
    handleResetFrom() {
      this.$refs.collegeFrom.resetFields()
      this.$refs.id.focus()
    }
  }
}
</script>
